<template>
  <div>
    <el-container>
      <el-header class="header" height="36px">
        <page_sub_title />
      </el-header>

      <el-main class="main-box">
        <div class="top-container">
          <div class="top-left">
            <div class="category">
              <el-segmented v-model="category" :options="categories" @change="getGoodList" />
            </div>
          </div>

          <div class="top-right">
            <el-button class="button" color="#53BEC9" @click="handleAdd">新增</el-button>
            <el-popconfirm placement="top" width="100" confirm-button-text="确定" cancel-button-text="取消" :hide-after="50"
              hide-icon title="要删除该商品吗？" @confirm="handleBatchDelete">
              <template #reference>
                <el-button class="button" color="#53BEC9">删除所选项</el-button>
              </template>
            </el-popconfirm>
            <el-input class="input" v-model="searchContent" placeholder="搜索" @change="getGoodList" clearable>
              <template #prefix>
                <i class="iconfont icon-search" />
              </template>
            </el-input>
          </div>
        </div>

        <el-table :data="goodData" highlight-current-row style="width: 100%" :row-style="{ height: '9vh' }"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column property="image" label="商品头图" width="100">
            <template #default="{ row }">
              <el-image v-if="row.image" style="width: 42px; height: 42px;" :src="getImageUrl(row.image)" />
              <el-image v-else style="width: 42px; height: 42px;" src="/public/logo.png" />
            </template>
          </el-table-column>
          <el-table-column property="title" label="商品名称" show-overflow-tooltip align="center" />
          <el-table-column property="price" width="120" label="销售价格" align="center" />
          <el-table-column property="stock" width="120" label="商品库存" align="center" />
          <el-table-column fixed="right" label="操作" width="200" align="center">
            <template #default="{ row }">
              <div class="operation-box">
                <div class="operation" @click="handleEdit(row)">
                  <i class="iconfont icon-edit" />
                </div>
                <el-popconfirm placement="top" width="100" confirm-button-text="确定" cancel-button-text="取消"
                  :hide-after="50" hide-icon title="要删除该商品吗？" @confirm="handleDelete(row.id)">
                  <template #reference>
                    <div class="operation">
                      <i class="iconfont icon-delete" />
                    </div>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination :total="dataTotal" :size="pageSize" :current="pageNo" @change="handlePageChange" />
      </el-main>
    </el-container>

    <div class="dialog-box">
      <el-dialog v-model="formDialogVisible" :title="formTitle" width="50%" top="10vh" center draggable>
        <el-form ref="formRef" label-width="auto" :model="formData" :rules="checkForm">
          <el-form-item label="商品头图">
            <el-upload class="upload-container" :show-file-list="false" :http-request="uploadSectionFile">
              <el-image v-if="formData.image" :src="getImageUrl(formData.image)" class="avatar" />
              <i v-else class="iconfont icon-plus icon" />
            </el-upload>
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input v-model="formData.title" placeholder="请输入商品名称" clearable />
          </el-form-item>
          <el-form-item label="销售价格">
            <el-input v-model="formData.price" placeholder="请输入销售价格" clearable />
          </el-form-item>
          <el-form-item label="商品库存">
            <el-input v-model="formData.stock" placeholder="请输入商品库存" clearable />
          </el-form-item>
          <el-form-item label="类目名称">
            <el-select v-model="formData.category" placeholder="选择类别" clearable>
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="footer">
            <el-button @click="formDialogVisible = false">取消</el-button>
            <el-button class="button" color="#53BEC9" @click="submitForm">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { getImageUrl } from '@/api/file';
import { ElMessage } from 'element-plus';
import page_sub_title from '@/components/page_sub_title.vue';
import pagination from '@/components/pagination.vue';
const route = useRoute();

onMounted(() => {
  getGoodList();
});

// 顶部分类栏
const category = ref('全部');
const categories = [
  { label: '全部', value: '全部' },
  { label: '宠物', value: '宠物' },
  { label: '宠物用品', value: '宠物用品' },
  { label: '其他', value: '其他' }
];

// 搜索内容
const searchContent = ref('');
const search = () => {
};

// 表格数据相关字段
const goodData = ref([]);
const dataTotal = ref(0);
const pageNo = ref(1);
const pageSize = ref(7);
// 获取数据
import { getGoodListService } from '@/api/goods';
const getGoodList = async () => {
  let goodQuery = {
    storeId: route.params.id,
    pageNo: pageNo.value,
    pageSize: pageSize.value,
    category: category.value !== '全部' ? category.value : '',
    keyWord: searchContent.value
  }
  const res = await getGoodListService(goodQuery)
  if (res.code === 0) {
    goodData.value = res.data.list
    dataTotal.value = parseInt(res.data.total)
    for (let i = 0; i < goodData.value.length; i++) {
      goodData.value[i].price = goodData.value[i].price / 100
    }
  }
}
watch(() => pageNo.value, getGoodList)

// 表单内容相关
const formTitle = ref('新增')
const formDialogVisible = ref(false)
const formData = ref({})
const options = [
  { value: '宠物', label: '宠物' },
  { value: '宠物用品', label: '宠物用品' },
  { value: '其他', label: '其他' }
]

// 新增
const handleAdd = () => {
  formData.value = {}
  openDialogVisible('add')
}

// 编辑
const handleEdit = (row) => {
  formData.value = JSON.parse(JSON.stringify(row))
  openDialogVisible('edit')
}

// 删除
import { deleteGoodService } from '@/api/goods';
const handleDelete = async (id) => {
  const res = await deleteGoodService(id)
  if (res.code === 0) {
    ElMessage.success(res.message)
    getGoodList()
  }
}

// 多选栏
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val.map((item) => item.id)
}

// 批量删除
import { batchDeleteGoodService } from '@/api/goods';
const handleBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的商品')
    return
  }
  const res = await batchDeleteGoodService(multipleSelection.value)
  if (res.code === 0) {
    ElMessage.success(res.message)
    getGoodList()
  }
}

// 打开对话框
const openDialogVisible = (type) => {
  if (type === 'add') {
    formTitle.value = '新增'
  } else if (type === 'edit') {
    formTitle.value = '编辑'
  }
  formDialogVisible.value = true
}

// 处理文件
import { uploadFileService } from '@/api/file';
const uploadSectionFile = async (param) => {
  let fileObj = param.file;
  let form = new FormData();
  // 文件对象
  form.append("file", fileObj);
  const res = await uploadFileService(form)
  if (res.code === 0) {
    formData.value.image = res.data
  }
}

// 表单校验规则
const checkForm = ref({
  title: [
    { required: true, message: '请输入商品名称', trigger: 'change' },
  ],
  price: [
    { required: true, message: '请输入销售价格', trigger: 'change' },
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'change' },
  ],
  category: [
    { required: true, message: '请选择类目', trigger: 'change' },
  ]
})

// 提交表单
import { addGoodService, updateGoodService } from '@/api/goods';
const formRef = ref()
const submitForm = () => {
  formRef.value.validate().then(async () => {
    formData.value.storeId = route.params.id
    formData.value.price = formData.value.price * 100
    let res
    if (formTitle.value === '新增') {
      res = await addGoodService(formData.value)
    } else if (formTitle.value === '编辑') {
      res = await updateGoodService(formData.value)
    }
    if (res.code === 0) {
      ElMessage.success(res.message)
      formDialogVisible.value = false
      getGoodList()
    }
  }).catch(() => { })
};

// 分页逻辑处理
const handlePageChange = (page) => {
  pageNo.value = page
};
</script>

<style scoped lang="scss">
.header {
  display: flex;
  justify-content: space-between;
}

.main-box {
  margin-top: 1vh;

  .top-container {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .top-left {
      background-color: #fff;
      border-radius: 10px 10px 0 0;
      display: flex;
      padding: 0 1vw;

      .el-segmented {
        --el-segmented-color: #273556;
        --el-segmented-bg-color: #fff;
        --el-segmented-item-selected-color: #53bec9;
        --el-segmented-item-selected-bg-color: #fff;
        --el-segmented-item-hover-bg-color: #f8f8f8;

        :deep(.el-segmented__item) {
          padding-top: 2vh;
          padding-bottom: 2vh;
        }

        :deep(.el-segmented__item-selected:after) {
          content: '';
          position: absolute;
          top: 0;
          left: 30%;
          bottom: 5px;
          height: 2px;
          width: 40%;
          background-color: #53bec9;
        }
      }
    }

    .top-right {
      display: flex;
      align-items: center;

      .button {
        color: #fff;
        border-radius: 6px;
      }

      .input {
        margin-left: 1vw;
        width: 220px;
      }
    }
  }

  .operation-box {
    display: flex;
    justify-content: center;
    align-items: center;

    .operation {
      width: 40px;
      height: 40px;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
    }
  }
}

.dialog-box {
  :deep(.el-dialog__body) {
    padding: 0 10%;
  }

  :deep(.el-dialog__footer) {
    display: flex;
    justify-content: center;
  }

  .upload-container {
    :deep(.el-upload) {
      border: 1px dashed #dcdfe6;
      border-radius: 6px;
      cursor: pointer;
      overflow: hidden;
      transition: 0.2s;
    }

    :deep(.el-upload:hover) {
      border-color: #67cad6;
    }

    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
  }

  .footer {
    width: 40%;
    display: flex;
    justify-content: space-between;

    .button {
      color: #fff;
    }
  }
}
</style>
